<template>
  <Modal v-model="visible" width="800" title="回款核销">
    <div class="count">
      <span>剩余应结佣金：{{ $dt.tool.formatterMoney(residue) }} 元</span>
      <span>上次剩余未核销金额：{{ $dt.tool.formatterMoney(info.writeOffSurplusAmount) }} 元</span>
    </div>
    <Table ref="table" border :columns="columns" :data="list">
      <template slot-scope="{ row, index }" slot="price">
        <Input v-model="row.price" @on-blur="onBlur(row, index)" type="number" placeholder="请输入核销金额" />
      </template>
    </Table>
    <div class="bottom">
      <p>已选择房源{{ selection.list.length }}套</p>
      <div>
        <p style="margin-right: 10px">默认按签约日期排序</p>
        <Button type="primary" :disabled="disabled" @click="onSelectRoom">分批核销房源设置</Button>
      </div>
    </div>

    <div slot="footer" class="footer">
      <Button @click="hide">取消</Button>
      <Button type="primary" @click="onConfirm">确认</Button>
    </div>

    <!-- 分批核销房源设置 -->
    <batch-writeoff ref="batch" @selection="onSelection" />
  </Modal>
</template>

<script>
  import moment from 'moment'
  import batchWriteoff from './batch-writeoff.vue'
  import informationMgr from '@/biz/commission/information.js'
  import table from '@/components/dt/table/render.js'
  import dt from '@dt/dt'

  export default {
    props: {
      data: Object,
      refresh: Function
    },
    components: {
      batchWriteoff
    },
    data() {
      return {
        visible: false,
        columns: [
          {
            type: 'index',
            title: '序号',
            width: 70
          },
          {
            key: 'backAmount',
            title: '回款金额(元)',
            width: 130,
            render: (h, { row }) => {
              return table.cell.text(h, {
                value: dt.tool.formatterMoney(row.backAmount)
              })
            }
          },
          {
            key: 'writeOffAmount',
            title: '已核销金额(元)',
            width: 130,
            render: (h, { row }) => {
              return table.cell.text(h, {
                value: dt.tool.formatterMoney(row.writeOffAmount)
              })
            }
          },
          {
            key: 'waitWriteOffAmount',
            title: '剩余金额(元)',
            width: 130,
            render: (h, { row }) => {
              return table.cell.text(h, {
                value: dt.tool.formatterMoney(row.waitWriteOffAmount)
              })
            }
          },
          {
            key: 'backDate',
            title: '回款日期',
            width: 120,
            render: (h, { row }) => {
              return h('span', row.backDate ? moment(row.backDate).format('YYYY-MM-DD') : '')
            }
          },
          {
            key: 'price',
            title: '核销金额(元)',
            slot: 'price'
          }
        ],
        list: [],
        roomList: [],
        disabled: true,
        info: {},
        selection: {
          list: [],
          total: 0
        }
      }
    },
    computed: {
      residue() {
        let num = 0
        if (this.info.preCommissionAmount) {
          let writtenOffAmount = this.info.writtenOffAmount || 0
          num = this.info.preCommissionAmount - writtenOffAmount
        }
        return this.$tool.precision(num)
      },
      writeoffTotal() {
        let total = this.list.reduce((num, { price }) => {
          num = price ? num + Number(price) : num
          return this.$tool.precision(num)
        }, 0)
        return this.info.writeOffSurplusAmount
          ? this.$tool.precision(total + Number(this.info.writeOffSurplusAmount))
          : total
      }
    },
    methods: {
      onConfirm() {
        let errorFlag = false
        for (let item of this.list) {
          if (!this.onValidate(item)) {
            errorFlag = true
            break
          }
        }
        if (!errorFlag) {
          let writeOffDetail = this.list.filter((i) => i.price)
          informationMgr
            .writeOff({
              commissionId: this.info.commissionId,
              writeOffDetail: writeOffDetail.map((i) => ({ backId: i.backId, writeOffAmount: i.price })),
              commissionDetailId: this.selection.list.map((i) => i.commissionDetailId)
            })
            .then((res) => {
              this.$Message.success('核销成功')
              this.$emit('success')
              this.hide()
            })
        }
      },
      // 分批核销房源设置
      onSelectRoom() {
        this.$refs.batch.show({
          commissionId: this.info.commissionId,
          list: this.roomList,
          selection: this.selection,
          writeoffTotal: this.writeoffTotal
        })
      },
      onSelection(data) {
        this.selection = data
      },
      onBlur(row, index) {
        this.list.splice(index, 1, row)
        if (this.onValidate(row)) {
          let total = this.list.reduce((num, { price }) => {
            num = price ? this.$tool.precision(num + Number(price)) : num
            return num
          }, 0)
          if (total == this.residue) {
            this.disabled = true
            this.selection.list = [...this.roomList]
          } else {
            this.disabled = false
            this.initSelection()
          }
        }
      },
      onValidate(item) {
        let reg = /^-{0,1}\d+(\.\d{1,2}){0,1}$/
        if (item.price) {
          if (!reg.test(item.price)) {
            this.$Message.error('核销金额保留两位小数')
            this.disabled = true
            return false
          }
          if (item.waitWriteOffAmount >= 0 && (item.price > item.waitWriteOffAmount || item.price < 0)) {
            this.$Message.error('核销金额不可大于本条剩余金额，且不可小于0')
            this.disabled = true
            return false
          }
          if (item.waitWriteOffAmount < 0 && (item.price < item.waitWriteOffAmount || item.price > 0)) {
            this.$Message.error('剩余金额小于0时，核销金额不可小于本条剩余金额，且不可大于0')
            this.disabled = true
            return false
          }
        }
        let total = this.list.reduce((num, { price }) => {
          num = price ? this.$tool.precision(num + Number(price)) : num
          return num
        }, 0)
        if (Math.abs(total) > Math.abs(this.residue)) {
          this.$Message.error('核销金额之和不可大于剩余应结佣金')
          this.disabled = true
          return false
        }
        if (total == 0) {
          this.$Message.error('核销金额之和不能为0')
          this.disabled = true
          return false
        }
        return true
      },
      // 初始化选中的房源
      initSelection() {
        let data = informationMgr.initSelection(this.roomList, this.writeoffTotal)
        this.selection = {
          list: data.selection,
          total: data.total
        }
      },
      // 查询核销列表
      // getList() {
      //   informationMgr.writeOffBackList(this.info.housesId).then((res) => {
      //     this.list = res.map((i) => ({
      //       ...i,
      //       price: ''
      //     }))
      //   })
      // },
      // 查询房源列表
      getRoomList() {
        informationMgr
          .writeOffRoomList({
            commissionId: this.info.commissionId,
            orderBy: 'contract_date'
          })
          .then((res) => {
            this.roomList = res
          })
      },
      show(info, list) {
        this.visible = true
        this.info = { ...info }
        this.disabled = true
        this.selection = {
          list: [],
          total: 0
        }
        this.list = list.map((i) => ({
          ...i,
          price: ''
        }))
        this.getRoomList()
      },
      hide() {
        this.visible = false
      }
    }
  }
</script>

<style lang="scss" scoped>
  .count {
    margin-bottom: 10px;
    span {
      margin-right: 30px;
    }
  }

  .bottom {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    > div {
      display: flex;
      align-items: center;
    }
  }

  .footer {
    text-align: center;
  }
</style>
